aspx
<asp:GridView ID="GV" runat="server" OnRowCreated="GV_RowCreated">
</asp:GridView>
aspx.cs
protected void GV_RowCreated(object sender, GridViewRowEventArgs e)
{
// 檢查是不是標題列
if (e.Row.RowType == DataControlRowType.Header)
{
// 建立自訂的標題
GridView gv = (GridView)sender;
TableCellCollection tcHeader = e.Row.Cells;
tcHeader.Clear();//清除自動生成的表頭
GridViewRow gvRow1 = Header_Row1();
GridViewRow gvRow2 = Header_Row2();
// 把這一列加到最上面
gv.Controls[0].Controls.AddAt(0, gvRow2);
gv.Controls[0].Controls.AddAt(0, gvRow1);
}
}
private GridViewRow Header_Row1()
{
GridViewRow gvRow = new
GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
// 增加 Department 欄位
TableCell tc1 = new TableCell();
tc1.Text = "Department";
tc1.ColumnSpan = 2; // 跨兩欄
tc1.RowSpan = 2; // 跨兩欄
Header_置中_粗體(tc1);
gvRow.Cells.Add(tc1);
// 增加 Employee 欄位
TableCell tc2 = new TableCell();
tc2.Text = "Employee";
tc2.ColumnSpan = 3; // 跨三欄
Header_置中_粗體(tc2);
gvRow.Cells.Add(tc2);
return gvRow;
}
private GridViewRow Header_Row2()
{
GridViewRow gvRow = new
GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
TableCell tc1 = new TableCell();
tc1.Text = "header1";
tc1.ColumnSpan = 1;
Header_置中_粗體(tc1);
gvRow.Cells.Add(tc1);
TableCell tc2 = new TableCell();
tc2.Text = "header2";
tc2.ColumnSpan = 1;
Header_置中_粗體(tc2);
gvRow.Cells.Add(tc2);
TableCell tc3 = new TableCell();
tc3.Text = "header3";
tc3.ColumnSpan = 1;
Header_置中_粗體(tc3);
gvRow.Cells.Add(tc3);
return gvRow;
}
private static void Header_置中_粗體(TableCell tc2)
{
tc2.HorizontalAlign = HorizontalAlign.Center;
tc2.Font.Bold = true;
tc2.Font.Size = 9;
}
ref
https://dolphins11.pixnet.net/blog/post/404457859